<?php

namespace app\shop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\shop\model\GrabBuyModel;
use app\shop\model\GoodsModel;
use app\shop\model\SpecItemModel;
use app\shop\model\SpecModel;
use app\shop\model\SpecPriceModel;


class GrabBuy extends Admin
{
    public function index()
    {
        $list = GrabBuyModel::getList();
        $item = $list->items();
        $page = $list->render();

        return ZBuilder::make('table')
            ->setPageTitle('抢购管理')
            ->hideCheckbox()
            ->addColumns([
                ['title','活动标题'],
                ['start_time','开始时间','datetime'],
                ['end_time','结束时间','datetime'],
                ['buy_num','已购买'],
                ['order_num','订单数'],
                ['right_button','操作']
            ])
            ->addTopButton('add')
            ->addRightButtons('edit,delete')
            ->setRowList($item)
            ->setPages($page)
            ->fetch();
    }

    public function add()
    {

        if(request()->isPost()){
            $this->store();
        }
        $goods_list = GoodsModel::getAll();
        $this->assign('goods_list',$goods_list);
        return $this->fetch();

    }

    public function edit($id=0)
    {
        if(request()->isPost()){
            $this->store();
        }
        $data = GrabBuyModel::getOne($id);
        $goods_list = GoodsModel::getAll();
        $data['start_time'] = date('Y-m-d H:i',$data['start_time']);
        $data['end_time'] = date('Y-m-d H:i',$data['end_time']);
        $this->assign('goods_list', $goods_list);
        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * pop弹窗选择商品
     */
    public function getgoods(){
        $list = GoodsModel::getAll();
        $btn_access = [
            'title' => '确定',
            'icon'  => 'fa fa-fw fa-key',
            'class' => 'btn btn-success',
            'href'  => url('add')
        ];
//        $page = $list->render();
        $rows = [
            ['id', 'ID'],
            ['name','商品名称'],
            ['cate_name','分类名称'],
            ['brand_name','品牌名称'],
            ['shop_price','价格']
        ];
        return ZBuilder::make('table')
            ->setPageTitle('商品列表')
            ->setTableName('goods')
            ->addColumns($rows)
            ->addTopButton('confim', $btn_access)
            ->setHeight('auto')
            ->setRowList($list)
            ->fetch();
    }

    public function access(){
        $data = input('post.');
        $data = json_encode($data);
        $this->redirect('GrabBuy/add',['ids'=>$data]);
        //$this->success('保存成功', null, '_parent_reload');
    }




    public function delete($ids = 0)
    {
        $res = GrabBuyModel::del($ids);
        if($res){
            $this->success('删除成功',url('index'));
        }else{
            $this->error('删除失败');
        }
    }

    private function store()
    {
        $data = input('post.');

        $id = input('id',0);

//        $validate = new \app\shop\validate\Pin();
//        if(!$validate->check($data)){
//            $this->error($validate->getError());
//        }
        $goods_ids = [];
        if(isset($data['item']) && $data['item'])
        {
            foreach($data['item'] as $k => $v)
            {
                $goods_id = $k;
                $goods_ids[] = $goods_id;
                foreach ($v as $k2=>$v2)
                {
                    $v2['price'] = trim($v2['price']);
                    $dataList[] = ['goods_id'=>$goods_id,'key'=>$k2,'key_name'=>$v2['key_name'],'price'=>$v2['price'],'pin_price'=>$v2['pin_price'],'grab_price'=>$v2['grab_price'],'store_num'=>$v2['store_num'],'pinstore_num'=>$v2['pinstore_num'],'grabstore_num'=>$v2['grabstore_num']];
                }

                SpecPriceModel::del($goods_id);
                db("spec_price")->insertAll($dataList);
            }
        }
        if(isset($data['goods']) && $data['goods']){
            foreach($data['goods'] as $k2 => $v2)
            {
                $goods_id = $k2;

                $goods_ids[] = $goods_id;
                $v2['grab_price'] = trim($v2['grab_price']);

                $da = ['grab_price'=>$v2['grab_price'],'grabstore_num'=>$v2['grabstore_num']];
                db('goods')->where('id',$goods_id)->update($da);
            }
        }
        unset($data['item']);
        unset($data['goods']);
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        $data['goods_ids'] = implode(",", $goods_ids);

        $res = GrabBuyModel::store($data, $id);
        if($res>=1||$res==0){
            $this->success('保存成功',url('index'));
        }else{
            $this->error('保存失败，请重试！');
        }
    }

    public function ajaxGetSpec()
    {
        $goods_ids = input('post.');
        if(isset($goods_ids['type']) && $goods_ids['type']=='edit'){
            $goods_ids['arr'] = explode(',',$goods_ids['arr']);
        }
        $goods_ids = array_unique($goods_ids['arr']);


        $type =  input('get.type'); //add edit
        $str = '';
        foreach ($goods_ids as $k=>$goods_id){
            $str .= "<table class='table table-bordered' id='spec_input_tab' style='margin-bottom: 15px;'>";
            $goods_info = GoodsModel::getOne($goods_id);
            $type_id = $goods_info['type_id'];
            if($type_id == 0){
                //无商品模型
                $str .="<tr>";
                $str .="<td><b>商品名称</b></td>
                <td><b>原价格</b></td>
                <td><b>拼团价格</b></td>
               <td><b>总库存</b></td>
               <td><b>拼团库存</b></td>
             </tr>";
                $str .= "<tr><td>{$goods_info['name']}</td>
                <td><input class='form-control' name='goods[$goods_id][shop_price]' value='{$goods_info['shop_price']}' readonly=''></td>
                <td><input class='form-control' name='goods[$goods_id][grab_price]' value='{$goods_info['grab_price']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)' onpaste='this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)'></td>
                <td><input class='form-control' name='goods[$goods_id][store_num]' value='{$goods_info['store_num']}' readonly='' onkeyup='this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)' onpaste='this.value=this.value.replace(/[^\d.]/g,&quot;&quot;)'></td>
                <td><input class='form-control' name='goods[$goods_id][grabstore_num]' value='{$goods_info['grabstore_num']}'>
                <input type='hidden' name='' value=''></td></tr></table>";
            }else{
                $goods_name = $goods_info['name'];
                $spec_list = SpecModel::getIdList($type_id);

                $spec_item = [];
                foreach($spec_list as $k => $v){
                    $spec_item[$v] = SpecItemModel::getIdList($v);
                }


                $items_id = SpecPriceModel::getKeyList($goods_id);
                $items_ids = [];
                foreach ($items_id as $k=>$v){
                    $_item = explode('_', $v);
                    $items_ids = array_merge($items_ids,$_item);
                }
                $items_ids = array_unique($items_ids);
                $items_has = [];    //该商品拥有的规格
                foreach ($items_ids as $k=>$v){
                    foreach ($spec_item as $k2=>$v2){
                        if(in_array($v,$v2))
                            $items_has[$k2][] = $v;
                    }
                }

                foreach ($items_has as $k => $v)
                {
                    $spec_arr_sort[$k] = count($v);
                }
                asort($spec_arr_sort); //按照键值对关联数组进行升序排序
                foreach ($spec_arr_sort as $key =>$val)
                {
                    $spec_arr2[$key] = $items_has[$key];
                }

                $clo_name = array_keys($spec_arr2);     //返回包含数组中所有键名的一个新数组
                $spec_arr2 = combineDika($spec_arr2); //  获取 规格的 笛卡尔积

                $spec = SpecModel::getColumn();
                $specItem = SpecItemModel::getColumn();

                $keySpecGoodsPrice = SpecPriceModel::getColumn($goods_id);
                $str .="<tr>";
                // 显示第一行的数据
                $str .=" <td><b>商品名称</b></td>";
                foreach ($clo_name as $k => $v)
                {
                    $str .=" <td><b>{$spec[$v]}</b></td>";
                }

                $str .="<td><b>原价格</b></td>
                <td><b>抢购价格</b></td>
               <td><b>总库存</b></td>
               <td><b>抢购库存</b></td>
             </tr>";
                // 显示第二行开始
                foreach ($spec_arr2 as $k => $v)
                {
                    $str .="<tr>";
                    $str .="<td class='link'>$goods_name</td>";
                    $item_key_name = array();
                    foreach($v as $k2 => $v2)
                    {
                        $str .="<td class='link'>{$specItem[$v2]['item']}</td>";
                        $item_key_name[$v2] = $spec[$specItem[$v2]['spec_id']].':'.$specItem[$v2]['item'];
                    }
                    ksort($item_key_name);
                    $item_key = implode('_', array_keys($item_key_name));
                    $item_name = implode(' ', $item_key_name);

                    isset($keySpecGoodsPrice[$item_key]['price']) ? false : $keySpecGoodsPrice[$item_key]['price'] = 0; // 价格默认为0
                    isset($keySpecGoodsPrice[$item_key]['grab_price']) ? false : $keySpecGoodsPrice[$item_key]['grab_price'] = 0; // 价格默认为0
                    isset($keySpecGoodsPrice[$item_key]['pin_price']) ? false : $keySpecGoodsPrice[$item_key]['pin_price'] = 0; // 价格默认为0
                    isset($keySpecGoodsPrice[$item_key]['store_num']) ? false : $keySpecGoodsPrice[$item_key]['store_num'] = 0; //库存默认为0
                    isset($keySpecGoodsPrice[$item_key]['grabstore_num']) ? false : $keySpecGoodsPrice[$item_key]['grabstore_num'] = 0; //库存默认为0
                    isset($keySpecGoodsPrice[$item_key]['pinstore_num']) ? false : $keySpecGoodsPrice[$item_key]['pinstore_num'] = 0; //库存默认为0

                    $str .="<td><input class='form-control' name='item[$goods_id][$item_key][price]' value='{$keySpecGoodsPrice[$item_key]['price']}' readonly /></td>";
                    $str .="<td><input class='form-control' name='item[$goods_id][$item_key][grab_price]' value='{$keySpecGoodsPrice[$item_key]['grab_price']}' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")'/></td>";
                    $str .="<td><input class='form-control' name='item[$goods_id][$item_key][store_num]' value='{$keySpecGoodsPrice[$item_key]['store_num']}' readonly onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")'/></td>";
                    $str .="<td><input class='form-control' name='item[$goods_id][$item_key][grabstore_num]' value='{$keySpecGoodsPrice[$item_key]['grabstore_num']}' />
                <input type='hidden' name='item[$goods_id][$item_key][key_name]' value='$item_name' />
                <input type='hidden' name='item[$goods_id][$item_key][pin_price]' value='{$keySpecGoodsPrice[$item_key]['pin_price']}' />
                <input type='hidden' name='item[$goods_id][$item_key][pinstore_num]' value='{$keySpecGoodsPrice[$item_key]['pinstore_num']}' /></td>";
                    $str .="</tr>";
                }
                unset($spec_arr_sort);
                unset($spec_arr2);
                $str .= "</table>";
            }

        }

        return $str;


    }



}